package com.zj.album.graphy.views;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.zj.album.R;
import com.zj.album.graphy.PhotographHelper;
import com.zj.album.utils.ToastUtils;

import java.lang.ref.WeakReference;

/**
 * Created by zhaojie on 2017/10/20.
 */

public class PhotoSelectedView extends FrameLayout {

    private FrameLayout selectedView, flNum, fl_Img;
    private RecyclerImageView iv_Img;
    private TextView tvNum;
    private View rootView;
    private boolean state = false;
    private String dataUri;
    private ChangeListener listener;
    private Animation animation_enter, animation_exit;
    private int index;
    private FrameLayout.LayoutParams flp;
    private WeakReference<Context> ref_Context;


    /**
     * 静态配置值，决定视图大小，建议使用屏幕宽度的整除数
     */
    private final float widthMargin = 5f;
    private final float heightMargin = 5f;

    public PhotoSelectedView(@NonNull Context context) {
        this(context, null, 0);
    }

    public PhotoSelectedView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PhotoSelectedView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.ref_Context = new WeakReference<>(context);
        rootView = LayoutInflater.from(ref_Context.get()).inflate(R.layout.v_photoselected, null, false);
        this.addView(rootView, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        selectedView = find(R.id.v_photoView_flSelected);
        fl_Img = find(R.id.v_photoView_flImg);
        tvNum = find(R.id.v_photoView_tvNum);
        flNum = find(R.id.v_photoView_flNum);
    }

    private <T extends View> T find(int id) {
        return (T) rootView.findViewById(id);
    }

    /**
     * 在设置数据之前调用
     */
    public void init(ChangeListener listener) {
        this.listener = listener;
        animation_enter = new AlphaAnimation(0.0f, 1.0f);
        animation_exit = new AlphaAnimation(1.0f, 0.0f);
        animation_enter.setDuration(400);
        animation_exit.setDuration(400);
    }

    public void setState(boolean isSelected) {
        this.state = isSelected;
        PhotographHelper.getHelper().addRankModule(state, index);
        setSelectedDisplay();
    }

    private void setSelectedDisplay() {
        tvNum.setSelected(state);
        tvNum.setText(state ? "" + listener.getCurRank(dataUri) : "");
        boolean b = PhotographHelper.getHelper().isNeedUpAnimate(dataUri);
        if (b) {
            if (animation_enter != null) animation_enter.cancel();
            if (animation_exit != null) animation_exit.cancel();
            selectedView.clearAnimation();
            if (state) {
                if (animation_exit != null) animation_exit.cancel();
                if (animation_enter != null) {
                    selectedView.startAnimation(animation_enter);
                }
            } else {
                if (animation_enter != null) animation_enter.cancel();
                if (animation_exit != null) {
                    selectedView.startAnimation(animation_exit);
                }
            }
        }
        selectedView.setVisibility(state ? VISIBLE : GONE);
    }

    public String getUri() {
        return dataUri;
    }

    public void setUri(int position, String uri) {
        this.index = position;
        this.dataUri = uri;
    }

    public void setImg(final String cacheNameCode, final int position, final String uri) {
        if (TextUtils.isEmpty(uri)) return;
        if (flp == null)
            flp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        if (iv_Img == null) iv_Img = new RecyclerImageView(ref_Context.get());
        fl_Img.addView(iv_Img, flp);
        iv_Img.post(new Runnable() {
            @Override
            public void run() {
                if (iv_Img != null)
                    loaImage(uri, iv_Img.getWidth(), iv_Img.getHeight());
            }
        });
        flNum.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    state = !state;
                    if (state)
                        if (listener.canSelected(PhotographHelper.getHelper().curSelectedSize(cacheNameCode))) {
                            changeSelected(uri, state, position);
                        } else {
                            listener.onFailedSelected();
                        }
                    else {
                        changeSelected(uri, state, position);
                    }
                } else {
                    ToastUtils.show(ref_Context.get(), "数据异常，请重新选择");
                    rootView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ((Activity) ref_Context.get()).finish();
                        }
                    }, 300);
                }
            }
        });
        fl_Img.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) listener.onImgClick(state, dataUri);
            }
        });
    }

    private void changeSelected(String uri, boolean state, int position) {
        PhotographHelper.getHelper().upDateAnimUrl(uri);
        listener.onSelectChange(position, state, uri);
    }

    public void clearImg() {
//        DebugUtils.e("onWindow Detach");
        fl_Img.removeAllViews();
        if (iv_Img != null) {
            iv_Img.setOnClickListener(null);
            loaImage("", 10, 10);
        }
    }

    public int getIndex() {
        return index;
    }

    private void loaImage(String uri, int w, int h) {
        if (TextUtils.isEmpty(uri)) {
            iv_Img.clear();
            iv_Img = null;
        } else {
            iv_Img.setImageUri(uri, w, h);
//            Picasso.with(ref_Context.get()).load(uri).centerCrop().resize(iv_Img.getWidth(), iv_Img.getHeight()).into(iv_Img);
        }
    }

    public interface ChangeListener {

        void onSelectChange(int position, boolean isSelected, String uri);

        boolean canSelected(int curNum);

        void onFailedSelected();

        void onImgClick(boolean isSelected, String uri);

        int getCurRank(String uri);
    }
}
